import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Tab, Button, Dialog } from '@alifd/next';
import { t } from '@lingui/macro';
import { uniqueId } from 'lodash';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useState, useRef } from 'react';
import { column } from '../stores/definitions';
import DrawerFooter from '@/components/DrawerFooter';

const tableId = uniqueId('tauTable-');

function PriceScheme({ channelId, modal, onCancel }) {
  const { channelStore: store } = useStore();
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [tabIndex, setTabIndex] = useState([]); // 总的数据
  const [pricesScheme, setPricesScheme] = useState([]); // 每一个tab的数据源
  const [currentPage, setCurrentPage] = useState(0); // 默认页数
  const [pageSize, setPageSize] = useState(10); // 每页显示的数据数量

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    (async () => {
      store._orderStatus = '0';
      await init();
    })();
  }, []);

  const init = async () => {
    try {
      await store.channelPrice(channelId);
      setTabIndex(toJS(store.prices));
      setPricesScheme([...toJS(store.prices[0].items[0].description)]);
    } catch (error) {
      console.error('错误', error);
    }
  };

  // 根据当前页码和每页数量获取当前页需要显示的数据
  const startIndex = currentPage * pageSize;
  const endIndex = startIndex + pageSize;
  const currentPageData = pricesScheme.slice(startIndex, endIndex);

  // tabs事件回调
  const handleOnChangeTabs = (v) => {
    store._orderStatus = v;
    const price = tabIndex[Number(v)];
    const list = price.items[0].description;
    setPricesScheme([...list]);
    setCurrentPage(0); // 初始化页数
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  return (
    <>
      <TauPage className="page-container">
        <div className="content">
          <Tab
            activeKey={store._orderStatus}
            onChange={(v) => handleOnChangeTabs(v)}
          >
            {tabIndex.map((item) => (<Tab.Item key={item.key} title={item.name} />))}
          </Tab>
          <TauTable
            instanceId={tableId}
            primaryKey="id"
            tableLayout="fixed"
            currentPage={currentPage}
            pageSize={pageSize}
            total={pricesScheme.length}
            onFetch={({ page, size }) => {
              setCurrentPage(page);
              size && setPageSize(size);
            }}
            dataSource={currentPageData}
            columns={[
              { title: t`编号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.priceIdx(i, currentPage, pageSize) },
              column('start', {}),
              column('end', {}),
              column('price.RMB', {}),
            ]}
          />
        </div>
      </TauPage>
      <DrawerFooter>
        <Button style={{ marginLeft: 8 }} onClick={() => handleCancel()}>{t`取消`}</Button>
      </DrawerFooter>
    </>
  );
}

export default observer(PriceScheme);
